package com.mgblog.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mgblog.utils.LogUtil;

/**
 * 用来设置一个些参数
 * 如：设置freemarker要用的basePath
 * @author meigang
 *
 */
@WebFilter("/*")
public class MGFilter implements Filter{

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		LogUtil.initLog4j();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		initBasePathForFreemarker(req);
		filterNoLoginUser(req,res);
		chain.doFilter(req, res);
	}
	
	private void initBasePathForFreemarker(HttpServletRequest req) {
		StringBuffer url = req.getRequestURL();  
		String basePath = url.delete(url.length() - req.getRequestURI().length(), url.length())
									.append(req.getServletContext().getContextPath()).append("/").toString();  
		//在一个session中设置basePath来给freemarker使用
		if(null == req.getSession().getAttribute("basePath")){
			req.getSession().setAttribute("basePath", basePath);
			System.out.println("设置basePath");
		}
	}
	//拦截为登陆用户，跳转到首页面
	private void filterNoLoginUser(HttpServletRequest req,HttpServletResponse response){
		String reqUrl = req.getRequestURL().toString();
		System.out.println(reqUrl);
		if(reqUrl.contains(".do")){
			if(null == req.getSession().getAttribute("loginUser")){
				try {
					System.out.println("reqUrl:"+reqUrl+"拦截到为登陆用户");
					req.getRequestDispatcher("gf_toIndex.do").forward(req, response);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
}
